package com.itstack.springframework.context.support;

import com.itstack.springframework.beans.BeansException;
import com.itstack.springframework.beans.ConfigurableListableBeanFactory;
import com.itstack.springframework.beans.factory.config.BeanFactoryPostProcessor;
import com.itstack.springframework.beans.factory.config.BeanPostProcessor;
import com.itstack.springframework.context.ConfigurableApplicationContext;
import com.itstack.springframework.core.io.DefaultResourceLoader;

import java.util.Map;

/**
 * ClassName:
 * Description: TODO
 *
 * @author: Guo Shuai
 * @version: 1.0
 * @Date: 2021\11\25 0025
 */
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {

    @Override
    public void refresh() throws BeansException {
        //1. 创建bean工厂 并加载BeanDefinitions
        refreshBeanFactory();

        //2. 获取bean工厂
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();

        //3. bean实例化之前执行
        invokeBeanFactoryPostProcessors(beanFactory);

        //4. 提前执行的操作
        registerBeanPostProcessors(beanFactory);

        //5. 提前实例化单例对象
        beanFactory.preInstantiateSingletons();
    }

    protected abstract void refreshBeanFactory() throws BeansException;

    protected abstract ConfigurableListableBeanFactory getBeanFactory();

    public void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessors = getBeansOfType(BeanFactoryPostProcessor.class);
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessors.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }

    public void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanPostProcessor> beanFactoryPostProcessors = getBeansOfType(BeanPostProcessor.class);
        for (BeanPostProcessor beanPostProcessor : beanFactoryPostProcessors.values()) {
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) {
        return getBeanFactory().getBeansOfType(type);
    }

    @Override
    public Object getBean(String beanName) {
        return getBeanFactory().getBean(beanName);
    }

    @Override
    public Object getBean(String beanName, Object... args) throws BeansException {
        return getBeanFactory().getBean(beanName, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return getBeanFactory().getBean(name, requiredType);
    }
}
